package other.edan.newpaas.corporation;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.data.model.BidManagement__c;
import com.rkhd.platform.sdk.data.model.PowerOfAttorney__c;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.OperateResult;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.trigger.DataResult;
import com.rkhd.platform.sdk.trigger.Trigger;
import com.rkhd.platform.sdk.trigger.TriggerRequest;
import com.rkhd.platform.sdk.trigger.TriggerResponse;
import org.apache.commons.lang.StringUtils;
import other.edan.newpaas.utils.ComUtils;
import other.edan.newpaas.utils.HCXObjectService;

import java.util.*;

/**
 * @Description 生成法人授权委托书编码
 */
public class CreateAuthCode implements Trigger {

    private static final Logger LOGGER = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "新增法人授权: 生成授权编号 ==> ";

    @Override
    public TriggerResponse execute(TriggerRequest request) throws ScriptBusinessException {
        LOGGER.debug(LOGGER_MSG + "触发开始");
        List<XObject> dataList = request.getDataList();
        List<DataResult> dataResultList = new ArrayList<>();
        List<XObject> objectList = new ArrayList<>();
        for (XObject xObject : dataList) {
            objectList.add(xObject);
            dataResultList.add(new DataResult(true, "", xObject));
        }

        PowerOfAttorney__c powerOfAttorney = (PowerOfAttorney__c) objectList.get(0);
        generateCode(powerOfAttorney);

        return new TriggerResponse(true, "处理完成", dataResultList);
    }

    public static void main(String[] args) throws Exception {
        PowerOfAttorney__c powerOfAttorney = new PowerOfAttorney__c();
        powerOfAttorney.setId(3648514931481235L);
        powerOfAttorney = HCXObjectService.get(powerOfAttorney);

        new CreateAuthCode().generateCode(powerOfAttorney);
    }

    /**
     * 生成授权编码  规则: 办事处编码 + FR + '-' + 年份 + 月份 + 序号
     * @param powerOfAttorney
     */
    public void generateCode(PowerOfAttorney__c powerOfAttorney) {
        try {
            LOGGER.info(LOGGER_MSG + "开始处理");

            // 获取办事处编码
            Long dataId = powerOfAttorney.getId();
            String sql = "select id,name,banshichuZhuli__c.residentOfficeCode__c officeCode__c,toubiaoZhuanyuan__c.bidGroupNo__c bidGroupNo__c " +
                    " from powerOfAttorney__c where id = " + dataId;
            JSONObject powerData = HCXObjectService.queryAllUseXoql(sql).get(0);
            LOGGER.info(LOGGER_MSG + "powerData: " + powerData);

            // 获取后缀编码 当前最新的投标管理
            String oriSuffixCode = "";
            String suffixCode = "";
            String officeCode = powerData.getString("officeCode__c"); // 办事处编码


            // 当前最新的法人授权数据
            if (StringUtils.isBlank(officeCode)) {
                officeCode = "XX";
                sql = String.format("select id,name from powerOfAttorney__c where banshichuZhuli__c.residentOfficeCode__c is null and id != %s" +
                        " order by createdAt desc limit 1", dataId);
            } else {
                sql = String.format("select id,name from powerOfAttorney__c where banshichuZhuli__c.residentOfficeCode__c = '%s' and  id != %s" +
                        " order by createdAt desc limit 1", officeCode, dataId);
            }
            List<JSONObject> bidArray = HCXObjectService.queryAllUseXoql(sql);
            if (bidArray.size() > 0) {
                // 新的编码或许序号
                String name = bidArray.get(0).getString("name");
                if (StringUtils.isNotBlank(name) && name.split("-").length > 1) {
                    oriSuffixCode = name;
                    suffixCode = name.split("-")[1];
                }
            }
            LOGGER.info(LOGGER_MSG + "suffixCode: " + suffixCode);

            // 获取序号
            Date date = new Date();
            String yearMonths = String.format("%ty%tm", date, date); // 年月 2409
            LOGGER.info(LOGGER_MSG + "yearMonths: " + yearMonths);
            int number = 1;
            if (StringUtils.isNotBlank(suffixCode)) {
                // 有值 判断办事处是否一致，一致则序号 + 1, 不一致序号则从01开始
                String oldYearMonths = suffixCode.substring(2, 6);
                String oldNumber = suffixCode.substring(6);
                String oldOfficeCode = oriSuffixCode.substring(0, 2); // 办事处编码
                if (Objects.equals(officeCode, oldOfficeCode) && Objects.equals(yearMonths, oldYearMonths)) {
                    number = Integer.valueOf(oldNumber) + 1;
                }
            }

            // 投标专员 投标组成员编码
            String bidGroupNo = powerData.getString("bidGroupNo__c");
            if (StringUtils.isBlank(bidGroupNo)) {
                bidGroupNo = "00";
            }

            // 拼接授权编码 规则: 办事处编码 + FR + '-' + 投标组成员编码 + 年份 + 月份 + 序号
            String authCode = String.format("%sFR-%s%s%02d", officeCode, bidGroupNo, yearMonths, number);
            LOGGER.info(LOGGER_MSG + "authCode: " + authCode);

            // 更新授权编码
            PowerOfAttorney__c upPowerOfAttorney = new PowerOfAttorney__c();
            upPowerOfAttorney.setId(dataId);
            upPowerOfAttorney.setName(authCode);
            OperateResult update = HCXObjectService.update(upPowerOfAttorney);
            LOGGER.info(LOGGER_MSG + "更新授权编码: " + update.getSuccess());

            LOGGER.info(LOGGER_MSG + "处理成功");
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(LOGGER_MSG + "处理异常: " + e.getMessage());
        }
    }


}
